package edu.controller;

import edu.service.PermissionService;
import edu.vo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/permissions")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 保存权限信息
     * @param permission 权限对象
     * @return 保存后的权限对象
     */
    @PostMapping
    public ResponseEntity<Permission> savePermission(@RequestBody Permission permission) {
        Permission savedPermission = permissionService.savePermission(permission);
        return new ResponseEntity<>(savedPermission, HttpStatus.CREATED);
    }

    /**
     * 根据 ID 获取权限信息
     * @param id 权限 ID
     * @return 权限对象的 Optional 包装
     */
    @GetMapping("/{id}")
    public ResponseEntity<Permission> getPermissionById(@PathVariable Integer id) {
        Optional<Permission> permissionOptional = permissionService.getPermissionById(id);
        return permissionOptional.map(permission -> new ResponseEntity<>(permission, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 获取所有权限信息
     * @return 权限列表
     */
    @GetMapping
    public ResponseEntity<List<Permission>> getAllPermissions() {
        List<Permission> permissions = permissionService.getAllPermissions();
        return new ResponseEntity<>(permissions, HttpStatus.OK);
    }

    /**
     * 根据 ID 删除权限信息
     * @param id 权限 ID
     * @return 无内容响应
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePermissionById(@PathVariable Integer id) {
        permissionService.deletePermissionById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 更新权限信息
     * @param id 权限 ID
     * @param permission 新的权限信息
     * @return 更新后的权限对象
     */
    @PutMapping("/{id}")
    public ResponseEntity<Permission> updatePermission(@PathVariable Integer id, @RequestBody Permission permission) {
        Permission updatedPermission = permissionService.updatePermission(id, permission);
        return updatedPermission != null ? new ResponseEntity<>(updatedPermission, HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}